package pku;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by yangxiao on 2017/11/14.
 */

public class Consumer {
	List<String> topics = new LinkedList<>();
	int readPos = 0;
	int count = 0;
	String queue;

	public void attachQueue(String queueName, Collection<String> t) throws Exception {
		if (queue != null) {
			throw new Exception("只允许绑定一次");
		}
		queue = queueName;
		topics.addAll(t);
	}

	public ByteMessage poll() throws Exception {
		ByteMessage re = null;
		// 首先在硬盘中取出topic，如果topic存在就取出全部数据，并将topic加锁，直到所有数据取完，然后释放掉topic数据，如果没有则跳到下一个topic，直到所有topic取完
		ArrayList<ByteMessage> listMsgtoTopic = null;
		for (int i = readPos; i < topics.size(); i++) {
			listMsgtoTopic = MessageStore.store.readObjectFromFile(topics.get(i));
			if (listMsgtoTopic != null) {
				for (int j = count; j < listMsgtoTopic.size(); j++) {
					count++;
					re = listMsgtoTopic.get(j);
					if(count == listMsgtoTopic.size()){
						count =0;
					}
					return re;
				}
			}
			readPos++;

		}
		return re;
	}
}
